<template>
  <div class="login-wrapper">
    <div class="modal">
      <!-- status-icon 验证之后输入框的图标 -->
      <el-form ref="userForm" :model="user" status-icon :rules="rules">
        <div class="title">火星</div>
        <el-form-item prop="userName">
          <el-input
            type="text"
            prefix-icon="el-icon-user"
            v-model="user.userName"
          />
        </el-form-item>
        <el-form-item prop="userPwd">
          <el-input
            type="password"
            prefix-icon="el-icon-view"
            v-model="user.userPwd"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="btn-login" @click="login">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, unref, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import utils from '../utils/utils';
import storage from '../utils/storage';

const { proxy } = getCurrentInstance();
const router = useRouter();
const store = useStore();
const userForm = ref();
const user = reactive({ userName: 'admin', userPwd: 'admin' });
const $api = proxy.$api;

const rules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  userPwd: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

// 登录
const login = () => {
  const form = unref(userForm);
  // form.resetFields(); // 表单重置

  // 表单验证
  form.validate(async (valid) => {
    if (valid) {
      await $api.login(user).then(async (res) => {
        store.commit('saveUserInfo', res);
        store.commit('removeTabAll', { title: '首页', name: '/welcome' });
        await loadAsyncRouters();
        router.push('/welcome');
      });
    }
  });
};
// 根据菜单动态生成路由
const loadAsyncRouters = async () => {
  let userInfo = storage.getItem('userInfo') || {};
  if (userInfo.token) {
    try {
      const { menuList } = await $api.getPermissionList();
      let routes = utils.generateRoute(menuList);
      routes.map((route) => {
        let url = `../views/${route.component}.vue`;
        route.component = () => import(url);
        router.addRoute('home', route);
      });
    } catch (error) {
      // console.log(error);
    }
  }
};
</script>

<style lang="scss">
.login-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f9fcff;
  width: 100vw;
  height: 100vh;
  .modal {
    width: 500px;
    padding: 50px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0px 0px 10px 3px #c7c9cb4d;
    .title {
      font-size: 50px;
      line-height: 1.5;
      text-align: center;
      margin-bottom: 30px;
    }
    .btn-login {
      width: 100%;
    }
  }
}
</style>
